<template>
  <div class="consultation-container">
    <el-card class="box-card" >
      <div slot="header" class="clearfix">
        <span>咨询管理</span>
        <div style="display: flex; justify-content: flex-end;">
          <el-tooltip class="item" effect="dark" content="发布公告" placement="top" style="margin-right: 75px">
            <el-badge  class="item">
              <el-button @click="declare()" size="mini" type="primary" icon="el-icon-magic-stick" circle></el-button>
            </el-badge>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="返回" placement="top" style="margin-right: 70px">
            <el-badge  class="item">
              <el-button @click="back()" size="mini" type="primary" icon="el-icon-thumb" circle></el-button>
            </el-badge>
          </el-tooltip>
        </div>
      </div>
      <el-table :data="pagedData" style="width: 1400px ; margin: auto" >
        <el-table-column prop="consultation_id" label="咨询ID" width="180">
        </el-table-column>
        <el-table-column prop="content" label="咨询内容">
        </el-table-column>
        <el-table-column prop="date" label="日期" width="200">
          <template slot-scope="scope">
            <!-- 可以在这里处理日期格式 -->
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column prop="from_whom" label="来自用户ID" width="120">
        </el-table-column>
        <el-table-column prop="is_processed" label="是否处理" width="120">
          <template slot-scope="scope">
            <el-button
                :type="scope.row.is_processed ? 'success' : 'danger'"
                @click="prepareDispose(scope.row)" >
              {{ scope.row.is_processed ? '已处理' : '未处理' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页控件 -->

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout=" prev, pager, next, total"
          :total="Consultations.length">
      </el-pagination>

      <el-dialog
          :visible.sync="dialogVisible"
          :title="'回复信息至用户 ' + to_userid"
          width="30%"
          @close="dialogVisible = false">
        <el-input
            type="textarea"
            v-model="inputContent"
            placeholder="请输入处理信息"
            rows="8"></el-input>
        <span slot="footer" class="dialog-footer">
      <el-button @click="cancle">取消</el-button>
      <el-button type="primary" @click="send">发送</el-button>
    </span>
      </el-dialog>

      <el-dialog
          :visible.sync="dialogVisible1"
          :title="'发布公告'"
          width="30%"
          @close="dialogVisible1 = false">
        <el-input
            type="textarea"
            v-model="inputContent"
            placeholder="请输入处理信息"
            rows="10"></el-input>
        <span slot="footer" class="dialog-footer">
      <el-button @click="cancledeclare">取消</el-button>
      <el-button type="primary" @click="senddeclare">发送</el-button>
    </span>
      </el-dialog>

    </el-card>

  </div>
</template>

<script>
import axios from "axios";
import Cookies from "js-cookie";

export default {
  name: "AdminNoticeView",
  data() {
    return {
      // 对话框显示标志
      dialogVisible: false,
      dialogVisible1:false,
      // 当前操作的行的数据，用于存储从哪里发来的信息或者其他标识
      currentRow: null,
      // 输入的内容
      inputContent: '',
      userid:0,
      Consultations: [],
      to_userid:0,
      to_consultation_id:0,
      currentPage: 1,
      pageSize: 8, // 默认每页显示的数据条数
      pagedData: [], // 当前页的数据
    };
  },
  created() {
    this.paginateData();
  },
  methods: {
    // 分页处理
    paginateData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.pagedData = this.Consultations.slice(start, end);
    },

    // 当改变每页显示的条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.paginateData();
    },

    // 当改变当前页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.paginateData();
    },
    declare(){
      this.dialogVisible1 = true;
    },
    senddeclare(){
      // 组装要发送的数据
      const postData = {
        to: 0,
        msg: this.inputContent
      };
      // 发送 POST 请求
      axios.post('http://127.0.0.1:5000/v1/messages/send_message', postData)
          .then(response => {
            // 请求成功处理
            console.log(response.data);
            // 清空输入区或做其他操作
            this.inputContent = '';
            this.dialogVisible1 = false;  // 如果需要在发送后关闭对话框
            this.$message({
              message: '发送成功',
              type: 'success'
            });
          })
          .catch(error => {
            // 请求失败处理
            console.error('发送消息失败:', error);
            alert('发送消息失败！');
          });
    },
    cancledeclare(){
      this.inputContent = ''; // 清空输入框
      this.dialogVisible1 = false;
    },
    cancle(){
      this.inputContent = ''; // 清空输入框
      this.dialogVisible = false;
    },
    prepareDispose(row) {
      if (row.is_processed) {
        this.$alert('已处理', '提示', {
          confirmButtonText: '确定',
          callback: () => {}
        });
      } else {
        this.to_userid = row.from_whom;
        this.to_consultation_id = row.consultation_id;
        this.currentRow = row;
        this.dialogVisible = true;
      }
    },
    send() {
      if (this.inputContent === '') {
        alert("请输入具体回复！");
        return;
      } else {
        // 组装要发送的数据
        const postData = {
          to: this.to_userid,
          msg: this.inputContent
        };
        // 发送 POST 请求
        axios.post('http://127.0.0.1:5000/v1/messages/send_message', postData)
            .then(response => {
              // 请求成功处理
              console.log(response.data);
              // 清空输入区或做其他操作
              this.inputContent = '';
              this.dialogVisible = false;  // 如果需要在发送后关闭对话框
            })
            .catch(error => {
              // 请求失败处理
              console.error('发送消息失败:', error);
              alert('发送消息失败！');
            });
        const updateData = {
          consultation_id: this.to_consultation_id
        }
        axios.post('http://127.0.0.1:5000/v1/admin/processConsultation', updateData,{ headers: { 'Content-Type': 'application/json', 'token': Cookies.get('token')} })
            .then(response => {
              // 请求成功处理
              console.log(response.data);
              this.$message({
                message: '更改成功',
                type: 'success'
              });
              this.update();
            })
            .catch(error => {
              // 请求失败处理
              console.error('更改消息失败:', error);
              alert('更改消息失败！');
            });
      }
    },
    update(){
      axios.get(`http://127.0.0.1:5000/v1/admin/getAllConsultations`, {
        headers: {
          'token': Cookies.get('token')
        }
      }).then((response) => {
        this.Consultations = response.data.data;
      }).catch((error) => {
        console.error("Error loading data:", error);
      });
    },
    dispose(id) {
      this.userid = id;
      alert(this.userid)
    },
    back() {
      this.$router.push({ name: 'home' });
    },
    formatDate(date) {
      if (!date) return '';
      console.log(date)
      date = date.replace(/\sGMT$/, '')
      // 使用Moment.js等库可方便处理日期格式，这里用原生方式演示
      let d = new Date(date);

      // 然后应用你的格式化代码
      date = d.getFullYear() + '-' +
            ('0' + (d.getMonth() + 1)).slice(-2) + '-' +
            ('0' + d.getDate()).slice(-2) + ' ' +
            ('0' + d.getHours()).slice(-2) + ':' +
            ('0' + d.getMinutes()).slice(-2) + ':' +
            ('0' + d.getSeconds()).slice(-2);

      return date
    }
  },
  mounted() {
    axios.get(`http://127.0.0.1:5000/v1/admin/getAllConsultations`, {
      headers: {
        'token': Cookies.get('token')
      }
    }).then((response) => {
      console.log(response.data);
      this.Consultations = response.data.data;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.pagedData = this.Consultations.slice(start, end);
    }).catch((error) => {
      console.error("Error loading data:", error);
    });
  }
};
</script>

<style scoped>
.consultation-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('../assets/1.png'); /* 替换 'path/to/your/image.jpg' 为你的图片路径 */
  background-size: cover; /* 覆盖整个容器 */
  background-position: center; /* 图片居中显示 */
}

.el-table .danger {
  background-color: #f56c6c;
  color: #fff;
}

.el-table .success {
  background-color: #67c23a;
  color: #fff;
}

.el-table .cell {
  padding: 8px; /* 默认为10px; 调整根据需求 */
}


</style>